/*
 *  SessionPlotter.java
 * 
 *  Created on May 24, 2008, 1:24:32 PM
 */

package pl.edu.agh.ssm.monitor.plotter;

import java.util.HashMap;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import pl.edu.agh.ssm.monitor.SessionMonitorView;
import pl.edu.agh.ssm.monitor.data.Session;
import pl.edu.agh.ssm.monitor.gui.SDPPanel;
import pl.edu.agh.ssm.monitor.gui.SessionGraphPanel;
import pl.edu.agh.ssm.monitor.visualization.MonitorDisplay;

/**
 *
 * @author aneezka
 */
public class SessionPlotter implements DataPlotter<Session> {

    public void plotNew(Session data) {
//    	System.out.println("New data to plot:" + data.getSessionDesc());
    	sessionsListModel.addElement(data);
        MonitorDisplay display = new MonitorDisplay();
        if(graphs.keySet().isEmpty()) {
        	panel.removeAll();
        	panel.add(display);
        }
        graphs.put(data, display);
//        System.out.println("Try to add graph to session:" + data.getId());
        SessionPlotterContainer.addGraph(data.getId(), display.getGraph());
//        System.out.println("Graph added");
    }

    public void plotUpdated(Session data) {
    	sdpPanel.updateSessionDescription(data.getSessionDescription());
    }

    public void plotRemoved(Session data) {
        sessionsListModel.removeElement(data);
        panel.removeAll();
        panel.revalidate();
        panel.repaint();
        graphs.remove(data);
        SessionPlotterContainer.removeGraph(data.getId());
        reloadSDPPanel();
    }

    public void prepareView(SessionMonitorView view) {
        System.out.println("SessionPlotter prepareView");
        view.addTab("Session", panel);
        view.addTab("SDP", sdpPanel);
        this.view = view;
        sessionsList = view.getSessionsList();
        sessionsList.setModel(sessionsListModel);
        sessionsList.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent arg0) {
                Session session = (Session) sessionsList.getSelectedValue();
                if (session != null && panel != null && graphs != null) {
                    panel.removeAll();
                    panel.add(graphs.get(session));
                    sdpPanel.updateSessionDescription(session.getSessionDescription());
                }
            }
            
        });
    }

    public void cleanView(SessionMonitorView view) {

    }
    
    private void reloadSDPPanel() {
        view.removeTab(sdpPanel);
        sdpPanel = new SDPPanel();
        view.addTab("SDP", sdpPanel);
    }

    SessionGraphPanel panel = new SessionGraphPanel();
    SDPPanel sdpPanel = new SDPPanel();
    JList sessionsList;
    DefaultListModel sessionsListModel = new DefaultListModel();
    HashMap<Session, MonitorDisplay> graphs = new HashMap<Session, MonitorDisplay>();
    SessionMonitorView view = null;
}
